/**
 * 
 */
package groovy.rule.participant;

import java.util.List;

import javax.annotation.Nullable;

import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;

import cn.boxiao.bxn.uic.model.Organization;
import cn.boxiao.bxn.uic.model.User;
import cn.boxiao.bxn.uic.rule.Rulable;
import cn.boxiao.bxn.uic.rule.participant.Participant.ParticipantType;
import cn.boxiao.bxn.uic.service.CustomTagService;
import cn.boxiao.bxn.uic.rule.participant.Participant;
/**
 *
 * @author tanxy
 * @since 2014-10-10
 */
public class GetUsersByTagRule implements Rulable<Participant> {
	@Autowired
	private CustomTagService tagService;
	/* (non-Javadoc)
	 * @see cn.boxiao.bxn.uic.rule.Rulable#run(java.lang.String)
	 */
	@Override
	public List<Participant> run(String param) {
		List<Participant> results = Lists.newArrayList();
		List<User> users = null;
		try{
			users = tagService.findUsersByTag(new Long(param));
			for(User u:users){
				results.add(buildParticipant(u));
			}
		}catch(Exception e){
			
		}
		return results;
	}
	private Participant buildParticipant(User user) {
        Participant participant = new Participant();
        participant.setParam(user.getId() + "");
        participant.setLabel(user.getFullname());
        participant.setActive(user.isValid());
        participant.setTarget(true);
        participant.setCode(user.getUniqueNo());
        participant.setNextRuleId(null);
        participant.setType(ParticipantType.USER);
        String orgIds = Joiner.on(",").join(Lists.transform(user.getOrganizations(), new Function<Organization, Long>() {
            @Override
            public Long apply(@Nullable Organization input) {
                return input.getId();
            }
        }));

        participant.setParentId(orgIds);

        participant.setSelfRuleId("getUsersByTagRule");

        return participant;
    }
	/* (non-Javadoc)
	 * @see cn.boxiao.bxn.uic.rule.Rulable#echo(java.util.List)
	 */
	@Override
	public List<Participant> echo(List<String> params) {
		return null;
	}

	/* (non-Javadoc)
	 * @see cn.boxiao.bxn.uic.rule.Rulable#echoUsers(java.util.List)
	 */
	@Override
	public List<User> echoUsers(List<String> params) {
		return null;
	}

}
